package cn.dckeji.gameBox.controller;

import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.xiaoleilu.hutool.setting.dialect.Props;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * cn.dckeji.lingcheng.controller
 * <p>Title:LingChengZhenGuanLi_Java</p>
 * <p>Description: 七牛上传</p>
 *
 * @author lucas
 * @version 1.0
 * @date 2017/12/11 20:03
 */
@RestController
@RequestMapping("/upload")
public class UpLoadImgController {

    @RequestMapping(value="fileUpload",method = RequestMethod.POST)
    public Map  fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException {
        //用来检测程序运行时间
        long  startTime=System.currentTimeMillis();
        System.out.println("fileName："+file.getOriginalFilename());
        String path=Thread.currentThread().getContextClassLoader().getResource("").toString();
        path=path.replace('/', '\\'); // 将/换成\
        path=path.replace("file:", ""); //去掉file:
        path=path.replace("classes\\", ""); //去掉class\
        path=path.substring(1); //去掉第一个\,如 \D:\JavaWeb...
        String fileName=new Date().getTime()+file.getOriginalFilename();
        String filePath=path+"\\images\\"+fileName;
        try {
            //获取输出流
            OutputStream os=new FileOutputStream(filePath);
            //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            InputStream is=file.getInputStream();
            int temp;
            //一个一个字节的读取并写入
            while((temp=is.read())!=(-1))
            {
                os.write(temp);
            }
            os.flush();
            os.close();
            is.close();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long  endTime=System.currentTimeMillis();
        System.out.println("方法一的运行时间："+String.valueOf(endTime-startTime)+"ms");
        Map pic = new HashMap();
        pic.put("src","../images/"+fileName);
        pic.put("title","pic");
        Map map = new HashMap();
        map.put("data",pic);
        map.put("code",0);
        return map;
    }

    /**
     * 上传多张图片到七牛
     * @return
     */
    @RequestMapping(value = "uploadManyImg",method = RequestMethod.POST)
    public Map imageUploadQiNiu(@RequestParam("file")MultipartFile[] files) throws IOException {
        //获取七牛配置信息
        Props props = new Props("qiniu.properties", "utf-8");
        String qiniuak = props.getStr("acceseKey");
        String qiniusk = props.getStr("sercretKey");
        String qiniubucket = props.getStr("bucket");
        String qiniudomain = props.getStr("domain");

        List<String> listImagePath=new ArrayList<String>();
        Map map = new HashMap();


        for (MultipartFile mf:files){
            if (!mf.isEmpty()){

                String name = mf.getOriginalFilename();

                //构造一个带指定Zone对象的配置类
                Configuration cfg = new Configuration(Zone.zone0());
                //...其他参数参考类注释
                UploadManager uploadManager = new UploadManager(cfg);

                Auth auth = Auth.create(qiniuak, qiniusk);
                String upToken = auth.uploadToken(qiniubucket);
                uploadManager.put(mf.getInputStream(), name, upToken, null, null);
                listImagePath.add(qiniudomain+"/"+name);
            }

        }
        map.put("data",listImagePath);
        map.put("errno",0);

        return map;

    }
    @RequestMapping(value = "getToken",method = RequestMethod.POST)
    public Map getToken(HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String,Object> maps=new HashMap<>();
        Props props = new Props("qiniu.properties", "utf-8");
        String qiniuak = props.getStr("acceseKey");
        String qiniusk = props.getStr("sercretKey");
        String qiniubucket = props.getStr("bucket");
        String qiniudomain = props.getStr("domain");
        Auth auth = Auth.create(qiniuak, qiniusk);
        String upToken = auth.uploadToken(qiniubucket);
        maps.put("token",upToken);
        maps.put("domain",qiniudomain);
        return maps;
    }


    /**
     * 上传单张图片到七牛
     * @return
     */
    @RequestMapping(value = "uploadOneImg",method = RequestMethod.POST)
    public Map imageUploadQiNiu(@RequestParam("file")MultipartFile file) throws IOException {


        //获取七牛配置信息
        Props props = new Props("qiniu.properties", "utf-8");
        String qiniuak = props.getStr("acceseKey");
        String qiniusk = props.getStr("sercretKey");
        String qiniubucket = props.getStr("bucket");
        String qiniudomain = props.getStr("domain");


        Map map = new HashMap();


        if (!file.isEmpty()){

            String name = file.getOriginalFilename();

            //构造一个带指定Zone对象的配置类
            Configuration cfg = new Configuration(Zone.zone0());
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);

            Auth auth = Auth.create(qiniuak, qiniusk);
            String upToken = auth.uploadToken(qiniubucket);
            uploadManager.put(file.getInputStream(), name, upToken, null, null);

            Map pic = new HashMap();
            pic.put("src",qiniudomain+"/"+name);
            pic.put("title","pic");
            map.put("data",pic);
        }

        map.put("code",0);
        return map;
    }
}
